package com.hankol.message;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import android.widget.ImageView;

import androidx.annotation.NonNull;

import com.baselibrary.utils.Config;
import com.baselibrary.utils.GsonUtils;
import com.baselibrary.utils.SpUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.hankol.message.bean.ChatUserInfoBean;
import com.hankol.message.bean.DynamicCardMessage;
import com.hankol.message.bean.FriendStateMessage;
import com.hankol.message.bean.IMUserBean;
import com.hankol.message.bean.ProduceModule;
import com.hankol.message.imConfig.CustomConversationProvider;
import com.hankol.message.imConfig.CustomDynamicCardMessageProvider;
import com.hankol.message.imConfig.CustomHQVoiceMessageItemProvider;
import com.hankol.message.imConfig.CustomImageMessageItemProvider;
import com.hankol.message.imConfig.CustomSightMessageItemProvider;
import com.hankol.message.imConfig.CustomTextMessageProvider;
import com.hankol.message.imConfig.FriendStateMessageProvider;
import com.hankol.message.imConfig.MyExtensionConfig;
import com.okhttp.SendRequest;
import com.okhttp.callbacks.GenericsCallback;
import com.okhttp.sample_okhttp.JsonGenericsSerializator;

import io.rong.imkit.GlideKitImageEngine;
import io.rong.imkit.RongIM;
import io.rong.imkit.config.RongConfigCenter;
import io.rong.imkit.conversation.extension.RongExtensionManager;
import io.rong.imkit.conversation.messgelist.provider.GroupNotificationMessageItemProvider;
import io.rong.imkit.conversation.messgelist.provider.HQVoiceMessageItemProvider;
import io.rong.imkit.conversation.messgelist.provider.ImageMessageItemProvider;
import io.rong.imkit.conversation.messgelist.provider.SightMessageItemProvider;
import io.rong.imkit.conversation.messgelist.provider.TextMessageItemProvider;
import io.rong.imkit.conversationlist.model.BaseUiConversation;
import io.rong.imkit.conversationlist.provider.PrivateConversationProvider;
import io.rong.imkit.userinfo.RongUserInfoManager;
import io.rong.imkit.utils.RouteUtils;
import io.rong.imkit.widget.adapter.ProviderManager;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.UserInfo;
import io.rong.message.GroupNotificationMessage;
import io.rong.push.RongPushClient;
import io.rong.push.pushconfig.PushConfig;
import io.rong.sight.SightExtensionModule;
import okhttp3.Call;

/**
 * @author 关忆北丶
 * @description:
 * @date :2021/4/16 11:34
 */
public class IMManager {
    private static final String TAG = "IMManager";
    public static ProduceModule mProduceModuleInstance;

    public static void iMInit(Application application) {
        initPush();
        RongIM.init(application, Config.RONG_APP_KEY, true);
        initCustomIMMes(application);
        initExtensionModule();
        RouteUtils.registerActivity(RouteUtils.RongActivityType.ConversationActivity, ConversationActivity.class);//注册好友列表页
        //头像修改为圆形
        initHeard();
        RongConfigCenter.conversationConfig().replaceMessageProvider(TextMessageItemProvider.class, new CustomTextMessageProvider());
        RongConfigCenter.conversationConfig().replaceMessageProvider(ImageMessageItemProvider.class, new CustomImageMessageItemProvider());
        RongConfigCenter.conversationConfig().replaceMessageProvider(SightMessageItemProvider.class, new CustomSightMessageItemProvider());
        RongConfigCenter.conversationConfig().replaceMessageProvider(HQVoiceMessageItemProvider.class, new CustomHQVoiceMessageItemProvider());
        //动态卡片
        RongConfigCenter.conversationConfig().addMessageProvider(new CustomDynamicCardMessageProvider());
        //好友状态提示
        RongConfigCenter.conversationConfig().addMessageProvider(new FriendStateMessageProvider());

    }

    //将聊天和好友界面的头像修改为圆形
    private static void initHeard() {
//        在App 初始之后调用以下代码进行设置
        RongConfigCenter.featureConfig().setKitImageEngine(new GlideKitImageEngine() {
            @Override
            public void loadConversationListPortrait(@NonNull Context context, @NonNull String url, @NonNull ImageView imageView, Conversation conversation) {
                Glide.with(imageView).load(url)
                        .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                        .into(imageView);
            }

            @Override
            public void loadConversationPortrait(@NonNull Context context, @NonNull String url, @NonNull ImageView imageView, Message message) {
                super.loadConversationPortrait(context, url, imageView, message);
                Glide.with(imageView).load(url)
                        .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                        .into(imageView);
            }
        });
    }

    /**
     * 初始化推送
     */
    private static void initPush() {
        //推送配置
        PushConfig config = new PushConfig
                .Builder()
                .enableHWPush(true)        // 在 AndroidManifest.xml 中搜索 com.huawei.hms.client.appid 进行设置
                .enableMiPush("2882303761518572504", "5791857211504")
                .enableMeiZuPush("133573", "8d93c53e9976486c8a13e8a3bf823bc0")
                .enableVivoPush(true)     // 在 AndroidManifest.xml 中搜索 com.vivo.push.api_key 和 com.vivo.push.app_id 进行设置
                .build();
        RongPushClient.setPushConfig(config);
    }

    /**
     * 初始化 + 号区域
     */
    public static void initExtensionModule() {
        //融云界面+号下扩展
        RongExtensionManager.getInstance().setExtensionConfig(new MyExtensionConfig());
        RongExtensionManager.getInstance().registerExtensionModule(new SightExtensionModule());
        mProduceModuleInstance = ProduceModule.getInstance();
        //IMManager.mProduceModuleInstance.upExtensionModule();
    }

    /**
     * 初始化自定义消息
     *
     * @param application
     */
    public static void initCustomIMMes(Application application) {
        RongIMClient.registerMessageType(GroupNotificationMessage.class);//自定义群通知消息
        RongIMClient.registerMessageType(DynamicCardMessage.class);//自定义动态卡片
        RongIMClient.registerMessageType(FriendStateMessage.class);//自定义好友关系提示
        RongIM.registerMessageTemplate(new GroupNotificationMessageItemProvider());//接受自定义群通知

        Conversation.ConversationType[] types = new Conversation.ConversationType[]{
                Conversation.ConversationType.PRIVATE,
                Conversation.ConversationType.GROUP,
                Conversation.ConversationType.DISCUSSION
        };
        RongIM.getInstance().setReadReceiptConversationTypeList(types);
        ProviderManager<BaseUiConversation> providerManager = RongConfigCenter.conversationListConfig().getProviderManager();//获取会话模板管理器
        providerManager.replaceProvider(PrivateConversationProvider.class, new CustomConversationProvider());//用自定义模板替换 SDK 原有模板

    }

    /**
     * 断开融云连接，不然关闭APP，无法接收到推送
     */
    public static void RongDisconnect() {
        RongIMClient.getInstance().disconnect();
    }


    public static void loadImInfo() {

        /*        RongUserInfoManager.getInstance().setGroupInfoProvider(new UserDataProvider.GroupInfoProvider() {
         *//**
         * 群信息回调
         * @param groupId 群组 ID
         * @return 群组信息
         *//*
            @Override
            public Group getGroupInfo(String groupId) {

                SendRequest.loadChatGroupInfo(SpUtils.getInstance().getLoadUserBean().getData().getToken(), groupId, new GenericsCallback<GroupInfoEntity>(new JsonGenericsSerializator()) {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                    }

                    @Override
                    public void onResponse(GroupInfoEntity response, int id) {
                        if (response.isSuccess()) {
                            Group groupinfo = new Group(groupId, response.getData().getName(),
                                    Uri.parse(response.getData().getIcon()));
                            RongIM.getInstance().refreshGroupInfoCache(groupinfo);
                        }
                    }
                });
                return null;
            }
        }, true);*/

        RongUserInfoManager.getInstance().setUserInfoProvider(userInfoId -> {
            SendRequest.getChatUserByUid(SpUtils.getInstance().getLoadUserBean().getData().getToken(), userInfoId, new GenericsCallback<ChatUserInfoBean>(new JsonGenericsSerializator()) {
                @Override
                public void onError(Call call, Exception e, int id) {

                }

                @SuppressLint("SetTextI18n")
                @Override
                public void onResponse(ChatUserInfoBean response, int id) {
                    if (response != null && response.getData() != null) {
                        ChatUserInfoBean.DataBean userInfoDataBean = response.getData();
                        UserInfo userInfo = new UserInfo(String.valueOf(userInfoDataBean.getId()), TextUtils.isEmpty(userInfoDataBean.getRemark()) ? userInfoDataBean.getName() : userInfoDataBean.getRemark(), Uri.parse(TextUtils.isEmpty(userInfoDataBean.getIcon()) ? "" : userInfoDataBean.getIcon()));
                        userInfo.setExtra(GsonUtils.toJson(new IMUserBean(userInfoDataBean.getIsFans())));
                        RongIM.getInstance().refreshUserInfoCache(userInfo);
                    }
                }
            });
            return null;
        }, true);

    }
}
